
package com.feib.soeasy.security;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import com.feib.soeasy.dao.UserLoginControlDao;
import com.feib.soeasy.model.User;
import com.feib.soeasy.model.UserActionLog;
import com.feib.soeasy.model.UserLoginControl;
import com.feib.soeasy.service.UserActionLogService;
import com.feib.soeasy.service.UserService;


/**
 * @title (#)SoeasyLogoutSuccessHandlerImpl.java<br>
 * @description <br>
 * @author Anson Tsai<br>
 * @version 1.0.0 2010/11/25
 * @copyright Far Eastern International Bank Copyright (c) 2010<br>
 * @2010/12/7 create by Anson Tsai<br>
 */
public class SoeasyLogoutSuccessHandlerImpl implements LogoutSuccessHandler {

    private static final Logger logger = LoggerFactory.getLogger(SoeasyLogoutSuccessHandlerImpl.class);
    
    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
    
    private String targetUrl;    

    @Autowired
    private UserActionLogService userActionLogService;

    @Autowired
    private UserService userService;
    
    @Autowired
    private UserLoginControlDao userLoginControlDao;
    
    
    /*
     * (non-Javdoc) 
     *
     * @see org.springframework.security.web.authentication.logout.LogoutSuccessHandler#onLogoutSuccess(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.springframework.security.core.Authentication)
     */
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        if (logger.isTraceEnabled()) {
            logger.trace("SoeasyLogoutSuccessHandlerImpl - start");
        }
        
        if (null != authentication)
        {
            String groupNo = null;// 帳單業者統一編號
            String userId = null;// 使用者名稱
            UserLoginControl c = null;
            User user = null;
            if (null != authentication.getPrincipal() && authentication.getPrincipal() instanceof SoeasyUserDetails) {
                logger.trace("從 Spring Security principal 取得 User 物件，依據User物件取得 UserLoginControl 物件");
                user = ((SoeasyUserDetails) authentication.getPrincipal()).getUser();                
                groupNo = user.getGroup().getGroupNo();
                userId = user.getUserId();
                c = userLoginControlDao.findByUer(user);                
            }
            else
            {
                logger.trace("從 Spring Security authentication 取得 帳號 與 業者代號，並依這兩個欄位取得 UserLoginControl 物件");
                /**
                 * 使用者登入群組帳號
                 */
                String name = authentication.getName();
                String[] userNameTemp = name.split("_conjunction_");
                groupNo = userNameTemp[0];// 帳單業者統一編號
                userId = userNameTemp[1];// 使用者名稱
                logger.trace("groupNo : " + groupNo);
                logger.trace("userId : " + userId);
                
                user = userService.queryByUerIdGroupNo(userId, groupNo);

                // 將使用者登入狀態改為False
                c = userLoginControlDao.findByUer(user); 
            }
             
            if (null != c)
            {
                c.setActived(Boolean.FALSE);
                c.setActivityTime(new Date());        
                userLoginControlDao.save(c);
            }
            
            //儲存UserActionLog記錄
            UserActionLog log = new UserActionLog();
            log.setInDateTime(new Date());
            log.setGroupPk(user.getGroup().getGroupPk());
            log.setGroupNo(user.getGroup().getGroupNo());
            log.setUserPk(user.getUserPk());
            log.setUserId(userId);
            log.setUsernName(user.getUserName());
            log.setActionBean("LogouActionBean");
            log.setEventName("logout");
            log.setLogNote("登出成功");
            if (null != authentication.getDetails())
            {
                log.setRemoteAddr(((WebAuthenticationDetails) authentication.getDetails()).getRemoteAddress());
            }         
            log.setOutDateTime(new Date());
            userActionLogService.addUserActionLog(log);
        }
        
        // 導向登入畫面
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.invalidate();
        }
        SecurityContextHolder.clearContext();
        
        // Redirect to target page.
        logger.trace("Redirect to targetUrl : " + targetUrl);
        redirectStrategy.sendRedirect(request, response, targetUrl);
        
        if (logger.isTraceEnabled()) {
            logger.trace("SoeasyLogoutSuccessHandlerImpl - end");
        }        
    }

    
    /**
     * @return 傳回 targetUrl。
     */
    public String getTargetUrl() {
        return targetUrl;
    }

    
    /**
     * @param targetUrl 要設定的 targetUrl。
     */
    public void setTargetUrl(String targetUrl) {
        this.targetUrl = targetUrl;
    }

}
